#include "IndexBuffer.h"
#include "D3D9Renderer.h"

UINT IndexBuffer::m_NumIndices;
UINT IndexBuffer::m_IndicesUsed;
IDirect3DIndexBuffer9* IndexBuffer::m_pIndexBuff;

IndexBuffer::IndexBuffer(void)
{
    m_pIndexBuff = 0;
    m_NumIndices = 0;
	m_IndicesUsed = 0;
}

IndexBuffer::~IndexBuffer(void)
{
    if(m_pIndexBuff)
	{
		m_pIndexBuff->Release();
		m_pIndexBuff = 0;
	}
}
    
void IndexBuffer::IncreaseIndices(UINT numIndices)
{
    // Implement a solution for the Renderer Lab
	UINT increments = (numIndices / s_IndexSizeIncrement) * s_IndexSizeIncrement + s_IndexSizeIncrement;
	m_NumIndices += increments;

	IDirect3DIndexBuffer9 *backup = m_pIndexBuff;

	void *bufferBackup;
	void *buffer;

	D3D9Renderer::device->CreateIndexBuffer(m_NumIndices * sizeof(UINT), D3DUSAGE_WRITEONLY, D3DFMT_INDEX32,  D3DPOOL_DEFAULT, &m_pIndexBuff, 0);
	if(backup)
	{
		m_pIndexBuff->Lock(0, (m_NumIndices) * sizeof(UINT), &buffer, 0);
		backup->Lock(0, (m_NumIndices) * sizeof(UINT), &bufferBackup, 0);
		memcpy(buffer, bufferBackup, (m_NumIndices-increments) * sizeof(UINT));
		backup->Unlock();
		m_pIndexBuff->Unlock();
		backup->Release();
	}


    //return IncreaseIndicesSolution(numIndices);
}

UINT IndexBuffer::AddIndices(const UINT* indices, UINT numIndices)
{
	UINT offset = m_IndicesUsed;

    // Implement a solution for the Renderer Lab
	if(m_IndicesUsed+numIndices > m_NumIndices)
		IncreaseIndices((m_IndicesUsed+numIndices)-m_NumIndices);

	void *buffer;
	m_pIndexBuff->Lock(offset*sizeof(UINT), numIndices * sizeof(UINT), &buffer, 0);
	memcpy(buffer, indices, numIndices * sizeof(UINT));
	m_pIndexBuff->Unlock();

	m_IndicesUsed += numIndices;

	return offset;
    //return AddIndicesSolution(indices, numIndices);
}

void IndexBuffer::Shutdown()
{
	if(m_pIndexBuff)
	{
		m_pIndexBuff->Release();
		m_pIndexBuff = 0;
	}
}